package cn.humaohua.study.yanmo_design_pattern.ch20;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class SecurityMgr {
    public static SecurityMgr instance = new SecurityMgr();

    public static SecurityMgr getInstance() {
        return instance;
    }

    private Map<String, Collection<Flyweight>> map = new HashMap<>();

    public void login(String user) {
        Collection<Flyweight> coll = queryByUser(user);
        map.put(user, coll);
    }

    public boolean hasPermit(String user, String securityEntity, String permit) {
        Collection<Flyweight> coll = map.get(user);
        for (Flyweight flyweight : coll) {
            if (flyweight.match(securityEntity, permit)) {
                return true;
            }
        }
        return false;
    }

    private Collection<Flyweight> queryByUser(String user) {
        Collection<Flyweight> coll = map.get(user);
        if (coll == null) {
            coll = new ArrayList<>();
            map.put(user, coll);
        }
        for (String db : TestDB.db) {
            String[] arr = db.split(",");
            if (StringUtils.equals(user, arr[0])) {
                //关键，从工厂里拿到单例的对象
                coll.add(FlyweightFactory.getInstance().getFlyweight(arr[1] + "," + arr[2]));
            }
        }
        return coll;
    }
}
